/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package org.apache.ranger.obs.server;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.minikdc.MiniKdc;

import java.io.File;
import java.util.Properties;

/**
 * description
 *
 * @since 2021-10-09
 */
public class MiniServer {
    private static MiniKdc miniKdc;

    private static File keytab;

    private Server server;

    private Configuration conf;

    private boolean isRunning = false;

    public MiniServer(Configuration conf) {
        this.conf = conf;
        conf.set("ranger.obs.service.dt.secret.provider", "org.apache.ranger.obs.security.token.MockSecretProvider");
        conf.set("ranger.obs.service.authorizer", "org.apache.ranger.obs.authorize.MockAuthorizer");
    }

    public static void startKdc(File workDir, String principal) throws Exception {
        Properties properties = MiniKdc.createConf();
        miniKdc = new MiniKdc(properties, workDir);
        miniKdc.start();
        keytab = new File(miniKdc.getKrb5conf().getParentFile(), "server_keytab");
        miniKdc.createPrincipal(keytab, principal);
    }

    public static void stopKdc() {
        if (miniKdc != null) {
            miniKdc.stop();
        }
    }

    public static String createClientPrincipal(String keytab_name, String principal) throws Exception {
        String keytab_path = null;
        if (miniKdc != null) {
            File keytab = new File(miniKdc.getKrb5conf().getParentFile(), keytab_name);
            miniKdc.createPrincipal(keytab, principal);
            keytab_path = keytab.getAbsolutePath();
        }
        return keytab_path;
    }

    public void start() throws Exception {
        this.conf.set("ranger.obs.service.kerberos.keytab", keytab.getAbsolutePath());
        this.server = new Server(conf);
        this.server.start();
        isRunning = true;
    }

    public void stop() {
        this.server.stop();

    }

    public boolean isRunning() {
        return isRunning && this.server.isRunning();
    }
}